package com.example.designpatterns.behavioral.momento;

import java.util.Stack;

/**
 * 管理者类
 *
 * @author scott
 */
public class HistoryManager {

    private final Stack<DocumentMemento> undoStack;
    private final Stack<DocumentMemento> redoStack;
    private final Document currentDocument;

    public HistoryManager(Document currentDocument) {
        this.undoStack = new Stack<>();
        this.redoStack = new Stack<>();
        this.currentDocument = currentDocument;
    }

    public void saveState() {
        undoStack.push(currentDocument.createMemento());
        // 清空重做栈
        redoStack.clear();
    }

    public void undo() {
        if (!undoStack.isEmpty()) {
            // 保存当前状态
            DocumentMemento currentState = currentDocument.createMemento();
            // 保存到重做栈
            redoStack.push(currentState);

            DocumentMemento memento = undoStack.pop();
            currentDocument.restoreFromMemento(memento);
        }
    }

    public void redo() {
        if (!redoStack.isEmpty()) {
            // 保存当前状态
            DocumentMemento currentState = currentDocument.createMemento();
            // 保存到撤销栈
            undoStack.push(currentState);

            DocumentMemento memento = redoStack.pop();
            currentDocument.restoreFromMemento(memento);
        }
    }

}
